from rest_framework import serializers
from django_redis import get_redis_connection
from .models import User


class Register(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8,max_length=20,label="密码",write_only=True)
    sms_code = serializers.CharField(min_length =6,max_length=6,label="短信验证码",write_only=True)
    allow = serializers.CharField(label="协议",write_only=True)
    token = serializers.CharField(label="令牌",read_only=True)
    class Meta:
        model = User
        fields = ('id','username','password','password2','mobile','sms_code','allow','token')

        read_only_fields = ['id']

        extra_kwargs = {
            "password":{
                "min_length":8,
                "max_length":20,
                "write_only":True
            }
        }

    def validate_allow(self,value):
        if value !="true":
            raise serializers.ValidationError("必须同意协议")
        return value

    def validata(self,attrs):
        #1.校验密码
        if attrs["password"] != attrs["password2"]:
            raise serializers.ValidationError("两次密码不一致")

        #2.校验短信验证码
        sms_code = attrs["sms_code"]
        mobile = attrs["mobile"]
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)

        if not redis_sms_code:
            raise serializers.ValidationError("验证码过期")

        #4.校验短信验证码是否正确
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        return attrs

    def create(self,validated_data):
        #1.删除不需要入库的字段
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        # #2.数据入库
        user = super(Register,self).create(validated_data)
        #2.1密码加密
        user.set_password(validated_data["password"])
        user.save()

        #3.创建token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        print(user.token)
        #4.返回数据
        return user
